package com.ksyzt.ksite2.server.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import com.google.gson.JsonObject;
import com.ksyzt.gwt.server.common.Thumbnail;
import com.ksyzt.gwt.server.common.Util;
import com.ksyzt.ksite2.server.common.Application;
import com.ksyzt.ksite2.server.database.dao.INEWSDAO;
import com.ksyzt.ksite2.server.database.dao.impl.NEWSDAOImpl;
import com.ksyzt.ksite2.shared.modle.NEWSObj;
import com.ksyzt.ksite2.shared.modle.PUSERObj;

public class TpzxUploadServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		JsonObject json = new JsonObject();

		Application app = new Application(request, response);

		String basePath = app.getBasePath();
		JsonObject r = new JsonObject();
		// 设置保存上传文件的目彄1�7
		String upext = "jpg,jpeg,gif,png"; // 上传扩展各1�7
		String localname = "";
		String err = "";
		String immediate = "";
		String attach_dir;
		String attach_subdir;
		String filename = "";
		String thmnbfilename = "";
		String fieldname = "";
		String extension = "";
		String target = "";
		String target_thumb = "";
		String filecontenttype = "";

		String uploadDir = getServletContext().getRealPath("upload");
		File fUploadDir = new File(uploadDir);

		if (!fUploadDir.exists()) {
			fUploadDir.mkdirs();
		}

		DiskFileUpload fu = new DiskFileUpload();
		// 最多上传10M数据
		fu.setSizeMax(1024 * 1024 * 10);
		// 超过1M的字段数据采用临时文件缓孄1�7
		fu.setSizeThreshold(1024 * 1024);
		// 采用默认的临时文件存储位罄1�7
		// fu.setRepositoryPath(...);
		// 设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码
		// fu.setHeaderEncoding("UTF8");

		// 得到扄1�7有表单字段对象的集合
		List fileItems = null;
		try {
			fileItems = fu.parseRequest(request);
		} catch (FileUploadException e) {
			err = "解析数据时出现如下问题：" + e.getMessage();
			e.printStackTrace();
		}
		if (fileItems != null) {
			// 处理每个表单字段
			Iterator i = fileItems.iterator();
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (fi.isFormField()) {
					String content = new String(fi.getString("UTF-8"));

					String fieldName = fi.getFieldName();
					System.out.println(fieldName + ":" + content);
					request.setAttribute(fieldName, content);
				}
			}
		}
		/*** 确定必要的变量 ******/
		String nid = (String) request.getAttribute("nid");
		String title = (String) request.getAttribute("title");
		String link = (String) request.getAttribute("link");
		String width = (String) request.getAttribute("width");
		String height = (String) request.getAttribute("height");

		int nwidth = 140;
		int nheight = 115;
		if (width != null && width.length() > 0) {
			nwidth = Integer.parseInt(width);
		}
		if (height != null && height.length() > 0) {
			nheight = Integer.parseInt(height);
		}
		if (fileItems != null) {
			// 处理每个表单字段
			Iterator item = fileItems.iterator();
			while (item.hasNext()) {
				FileItem fi = (FileItem) item.next();
				if (fi.isFormField()) {

				} else {
					try {
						String pathSrc = fi.getName();
						localname = pathSrc;
						if (pathSrc.trim().equals("")) {
							continue;
						}

						extension = pathSrc
								.substring(pathSrc.lastIndexOf(".") + 1);
						extension = extension.toLowerCase();
						if (("," + upext + ",").indexOf("," + extension + ",") < 0) {
							err = "上传文件扩展名必为：" + upext;
						} else {
							Date now = new Date();
							attach_subdir = "day_"
									+ Util.getDateString(now.getTime(),
											"yyMMdd");

							attach_dir = fUploadDir + "/" + attach_subdir + "/";
							File tempFile = new File(attach_dir);
							if (!tempFile.exists()) {
								tempFile.mkdirs();
							}
							filecontenttype = fi.getContentType();
							// 生成随机文件

							filename = Util.randomString(8) + "." + extension;
							thmnbfilename = filename.substring(0,
									filename.lastIndexOf("."))
									+ "_s.jpg";
							target = "upload/" + attach_subdir + "/" + filename;

							json.addProperty("path", target);

							File pathDest = new File(attach_dir + filename);
							fi.write(pathDest);

							Thumbnail nail = new Thumbnail(attach_dir
									+ filename, attach_dir + thmnbfilename);
							nail.resize(140, 115);
							target_thumb = "upload/" + attach_subdir + "/"
									+ thmnbfilename;

							fieldname = fi.getFieldName();

						}
					} catch (Exception e) {

						err = "存储文件时出现如下问题：" + e.getMessage();
						e.printStackTrace();
					} finally // 总是立即删除保存表单字段内容的临时文仄1�7
					{
						fi.delete();
					}
				}
			}
		}

		if (err.length() == 0) {
			/*************** save to attatchment table ********/
			try {
				if (nid != null && !nid.equals("")) {

					INEWSDAO dao = new NEWSDAOImpl(Application.getConnection());
					NEWSObj n = new NEWSObj();

					if (title == null || title.length() == 0) {
						title = "请输入标题";
					}
					n.setOID(Integer.valueOf(nid));
					n.setADDTIME(Util.getCurrentSQLTimestamp());
					n.setAUTHOR("系统");
					n.setCONTENT(title);
					n.setLINK(link);
					n.setCSS("");
					n.setDISPLAY(1);
					n.setICON(target);
					n.setISSYS(0);
					n.setORIGION("系统");
					n.setRANKVAL(0);
					n.setSTATUS(1);
					n.setSUMMARY(title);
					n.setTAG("图片");
					n.setVIEWER(0);
					n.setTITLE(title);
					PUSERObj u = app.getCurrentUser();
					int uid = u == null ? 0 : u.getID();
					n.setUSERID(uid);
					dao.insertObject(n);
				}
			} catch (SQLException e) {
				err = e.getMessage();
				e.printStackTrace();
			}
		}
		int msgtype = 2; // 返回上传参数的格式：1，只返回url＄1�7�返回参数数组1�7
		target = basePath + target;
		if (immediate != null && immediate.equals("1")) {
			target = "!" + target;
		}

		if (msgtype == 1) {
			r.addProperty("msg", (target));
		} else {
			json.addProperty("url", (target));
			json.addProperty("nid", nid);
			json.addProperty("title", title);
			r.addProperty("msg", (target));
			r.add("data", json);
		}

		r.addProperty("err", (err));

		out.print(r.toString());

		out.flush();
		out.close();
	}
}
